<?php

namespace app\admin\controller;

use app\admin\model\goods_manage\Goods;
use app\common\controller\Backend;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use think\Db;
use app\admin\model\Returnpurchasedetail as ReturnpurchasedetailModel;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Returnpurchasedetail extends Backend
{

    /**
     * Purchase模型对象
     * @var \app\admin\model\Purchase
     */
    protected $model = null;
    protected $agent_id = -1;
    protected $store_no = -1;
    protected $admin_id = -1;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Returnpurchasedetail;
        $this->view->assign("statusList", $this->model->getStatusList());

        $user_info = Session::get('admin');//获取当前登录用户信息
        $this->agent_id = $user_info['agent_id'];
        $this->store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        $all_goods_tmp = Goods::where('agent_id',$this->agent_id)->where('store_no',$this->store_no)->select();
        $all_goods = [];
        if($all_goods_tmp){
            foreach ($all_goods_tmp as $item){
                $all_goods[$item->id] = $item->goods_name;
            }

        }
        $this->view->assign("goodsList", $all_goods);

    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $purchase_id = $this->request->param('return_purchase_id');
        $p_status = $this->request->param('p_status');
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null);
            if($purchase_id){
                $list = $this->model
                    ->where($where)
                    ->where('return_purchase_id', $purchase_id)
                    ->where('agent_id', $this->agent_id)
                    ->where('store_no', $this->store_no)
                    ->where('admin_id', $this->admin_id)
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                //清除数据（清除purchase_id=0,admin_id的数据）
//                $this->model->where('purchase_id',0)->where('admin_id',$this->admin_id)->delete();
                $list = $this->model
                    ->where($where)
                    ->where('return_purchase_id', 0)
                    ->where('agent_id', $this->agent_id)
                    ->where('store_no', $this->store_no)
                    ->where('admin_id', $this->admin_id)
                    ->order($sort, $order)
                    ->paginate($limit);
            }
            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['money' => mt_rand(100000, 999999), 'price' => 200]);

            return json($result);
        }

        $this->view->assign("return_purchase_id", $purchase_id);
        $this->view->assign("p_status", $p_status);

        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $purchase_id_tmp = $this->request->param('return_purchase_id');
        $purchase_id = $purchase_id_tmp ? $purchase_id_tmp : 0;
        if (false === $this->request->isPost()) {
            $this->view->assign("return_purchase_id", $purchase_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $insert_tmp['agent_id'] = $this->agent_id;
            $insert_tmp['store_no'] = $this->store_no;
            $insert_tmp['admin_id'] = $this->admin_id;
            $insert_tmp['return_purchase_id'] = 0;//表示临时数据
            $insert_info = [];
            if(isset($params['goods_id']) && $params['goods_id']){
                //查询现有临时数据
                $all_purchase_detail = $this->model
                    ->where('return_purchase_id', $purchase_id)
                    ->where('agent_id', $this->agent_id)
                    ->where('store_no', $this->store_no)
//                    ->where('admin_id', $this->admin_id)
                    ->select();
                $all_purchase_detail_arr = [];
                if($all_purchase_detail){
                    foreach ($all_purchase_detail as $vvv){
                        $all_purchase_detail_arr[] = $vvv->goods_id;
                    }
                }
                $all_goods_arr = Goods::where('agent_id', $this->agent_id)
                    ->where('store_no', $this->store_no)
                    ->select();
                $all_goods = [];
                if($all_goods_arr){
                    foreach ($all_goods_arr as $valll){
                        $all_goods[$valll->id] = $valll;
                    }
                }

                foreach ($params['goods_id'] as $item){
                    if(!in_array($item,$all_purchase_detail_arr)){
                        $insert_tmp['goods_id'] = $item;
                        if(isset($all_goods[$item]) && $all_goods[$item]){
                            $goods_info = $all_goods[$item];
                            $insert_tmp['goods_name'] = $goods_info->goods_name;
                            $insert_tmp['supplier_id'] = $goods_info->supplier_id;
                            $insert_tmp['return_purchase_id'] = $params['return_purchase_id'];
                        }

                        $insert_info[] = $insert_tmp;
                        unset($insert_tmp['goods_id']);
                    }
                }
                $result = $this->model->allowField(true)->saveall($insert_info);
            }


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function ajchange()
    {
        $type = $this->request->param('type');
        $idss = $this->request->param('idss');
        $changething = $this->request->param('changething');
        var_dump($type);
        var_dump($idss);
        var_dump($changething);
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(isset($params['goods_id']) && $params['goods_id']){
                $goods_info = Goods::get($params['goods_id']);
                $params['goods_name'] = $goods_info->goods_name;
                $params['supplier_id'] = $goods_info->supplier_id;
                $is_exist = ReturnpurchasedetailModel::where('goods_id',$params['goods_id'])
                    ->where('return_purchase_id',$row->return_purchase_id)
                    ->where('id','<>',$row->id)
                    ->select();
                if($is_exist){
                    $this->error(__('已经存在同样的数据'));
                }
            }

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
